import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_dk_form/flutter_dk_form.dart';
import 'package:unicorndial/unicorndial.dart';

class DkFormDemoPage extends StatefulWidget {
  static const String routeName = '/page/dkform_demo_page';
  static const String name = "DkFormDemoPage";

  @override
  _FormDemoState createState() => _FormDemoState();
}

class _FormDemoState extends State<DkFormDemoPage> {
  GlobalKey<DkFormState> _formKey = GlobalKey<DkFormState>();

  void _forSubmitted() {
    var _form = _formKey.currentState;

    if (_form.validate(selfShowError: false)) {
      _form.save();
      print(json.encode(_form.value));
    }
    print('error text:${_form.errorText}');
  }

  void _forReset() {
    var _form = _formKey.currentState;
    _form.reset();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter DkForm',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter DkForm'),
        ),
        floatingActionButton: UnicornDialer(
          backgroundColor: Color.fromRGBO(255, 255, 255, 0.6),
          parentButtonBackground: Colors.redAccent,
          orientation: UnicornOrientation.VERTICAL,
          parentButton: Icon(Icons.add),
          childButtons: createButtons(),
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: DkForm(
            initialValue: jsonDecode(r'{"male":true,"drop_down_name":"One","drop_down_name_para":["One","Three"],"name":"123","pwd":"123456","contract":{"phone":{"phone_work":"13888888888","phone_home":"13666666666"},"email":"abc@163.com"},"movie":[{"name":"双面杀手","nation":"美国"},{"name":"我的国","nation":"中国"}]}'),
            key: _formKey,
            child: Column(
              children: <Widget>[
                DkSwitchFormField(
                  attribute: 'male',
                  initialValue: false,
                  title: '男',
                ),
                DkDropDownButtonFormField(
                  attribute: 'drop_down_name',
                  list: ['One','Two'],
                ),
                DkTextFormField(
                  attribute: 'name',
                  initialValue: 'gulliver',
                  decoration: InputDecoration(
                    labelText: 'Your Name',
                  ),
                ),
                DkTextFormField(
                  attribute: 'pwd',
                  initialValue: '123456',
                  decoration: InputDecoration(
                    labelText: 'Password',
                  ),
                  validator: (val) {
                    return val.length < 4 ? "密码长度错误" : null;
                  },
                ),
                ContractForm(),
                MovieForm(),
                DkMultipleInputFormField(
                  attribute: 'comment',
                  title: '留言',
                  initialValue: '12345',
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  List<UnicornButton> createButtons() {
    var childButtons = List<UnicornButton>();
    childButtons.add(UnicornButton(
      currentButton: FloatingActionButton(
        heroTag: 'reset',
        child: Text('Rest'),
        onPressed: _forReset,
      ),
    ));
    childButtons.add(UnicornButton(
      currentButton: FloatingActionButton(
        child: Text('Save'),
        onPressed: _forSubmitted,
      ),
    ));
    return childButtons;
  }
}

/// 自定义的FormField
class DropdownWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DkFormField(
      initialValue: 'Two',
      attribute: 'drop_down_name',
      validator: (value) {
        return value == 'One' ? "密码长度错误" : null;
      },
      builder: (DkFormFieldState<dynamic> field) {
        return InputDecorator(
          decoration: InputDecoration(
            labelText: 'Select option',
            contentPadding: EdgeInsets.only(top: 10.0, bottom: 0.0),
            border: InputBorder.none,
            errorText: field.errorText,
          ),
          child: DropdownButton(
            isExpanded: true,
            items: ["One", "Two"].map((option) {
              return DropdownMenuItem(
                child: Text("$option"),
                value: option,
              );
            }).toList(),
            value: field.value,
            onChanged: (value) {
              field.didChange(value);
            },
          ),
        );
      },
    );
  }
}

/// DkFormFieldList DkFormFieldListItem
class MovieForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DkFormFieldList(
      attribute: 'movie',
      child: Column(
        children: <Widget>[
          DkFormFieldListItem(
            index: 0,
            child: Column(
              children: <Widget>[
                DkTextFormField(
                  attribute: 'name',
                  initialValue: '双面杀手',
                  decoration: InputDecoration(
                    labelText: '电影名称',
                  ),
                ),
                DkTextFormField(
                  attribute: 'nation',
                  initialValue: '美国',
                  decoration: InputDecoration(
                    labelText: '地区',
                  ),
                ),
              ],
            ),
          ),
          DkFormFieldListItem(
            index: 1,
            child: Column(
              children: <Widget>[
                DkTextFormField(
                  attribute: 'name',
                  initialValue: '我的国',
                  decoration: InputDecoration(
                    labelText: '电影名称',
                  ),
                ),
                DkTextFormField(
                  attribute: 'nation',
                  initialValue: '中国',
                  decoration: InputDecoration(
                    labelText: '地区',
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class ContractForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DkFormFieldGroup(
      attribute: 'contract',
      child: Column(
        children: <Widget>[
          Text('联系方式'),
          DkFormFieldGroup(
            attribute: 'phone',
            child: Column(
              children: <Widget>[
                DkTextFormField(
                  attribute: 'phone_work',
                  initialValue: '13888888888',
                  decoration: InputDecoration(
                    labelText: '工作电话',
                  ),
                  validator: (value) {
                    RegExp mobile = new RegExp(r"1[0-9]\d{9}$");
                    return !mobile.hasMatch(value) ? '电话号码格式不正确' : null;
                  },
                ),
                DkTextFormField(
                  enabled: false,
                  attribute: 'phone_home',
                  initialValue: '13666666666',
                  decoration: InputDecoration(
                    labelText: '家庭电话',
                  ),
                ),
              ],
            ),
          ),
          DkTextFormField(
            enabled: true,
            attribute: 'email',
            initialValue: 'abc@163.com',
            decoration: InputDecoration(
              labelText: '电子邮箱',
            ),
          ),
        ],
      ),
    );
  }
}
